<?php



function genchksum13($ISBN10) 
{  
$ISBN10 = trim($ISBN10);  
  for ($i = 0; $i <= 12; $i++) 
  {  
  $tc = substr($ISBN10, -1, 1);  
  $ISBN10 = substr($ISBN10, 0, -1);  
  $ta = ($tc*3);  
  $tci = substr($ISBN10, -1, 1);  
  $ISBN10 = substr($ISBN10, 0, -1);  
  $tb = $tb + $ta + $tci;  
  }  

$tg = ($tb / 10);  
$tint = intval($tg);  

  if ($tint == $tg) 
  {
	  return 0;
  }  

$ts = substr($tg, -1, 1);  
$tsum = (10 - $ts);  

return $tsum;  

}  

function isbn10_to_13($ISBN10) 
{  
$ISBN10 = trim($ISBN10);  

  if(strlen($ISBN10) == 12)
  {
	  // if number is UPC just add zero  
  $ISBN1013 = '0'.$ISBN10;
  }  
  else  
  {  
  $ISBN102 = substr("978" . trim($ISBN10), 0, -1);  
  $sum13 = genchksum13($ISBN102);  
  $ISBN1013 = "$ISBN102$sum13";  
  }  
return ($ISBN1013);  
}  



function validate_isbn ($ISBNdata)
{
	if (strlen($ISBNdata)==10)
	{
	//parse ISBN into array
	$ch=str_split($ISBNdata,1);
	//calculate check digit by multiplying out first 9 digits
	$check=($ch[0]*10)+($ch[1]*9)+($ch[2]*8)+($ch[3]*7)+($ch[4]*6)+($ch[5]*5)+($ch[6]*4)+($ch[7]*3)+($ch[8]*2);
	//take the modulus. This is the correct check digit
	$check=$check % 11;

	//get check digit from input
	//account for 'x' check digit
		if ($ch[9]=='x')
		{
		$checkdigit=10;
		}
		else
		{
		$checkdigit=$ch[9];
		}
		
		if ($checkdigit==$check)
		{
		return "ISBN is valid";
		}
		else
		{
		return "ISBN is invalid";
		}



	}
	else if (strlen($ISBNdata)==13)//validate ISBN13 
	{
	//parse ISBN into array
	$ch=str_split($ISBNdata,1);
	//calculate check digit by multiplying out
	$check=($ch[0]*1)+($ch[1]*3)+($ch[2]*1)+($ch[3]*3)+($ch[4]*1)+($ch[5]*3)+($ch[6]*1)+($ch[7]*3)+($ch[8]*1)+($ch[9]*3)+($ch[10]*1)+($ch[11]*3);
	//take the modulus
	$check=$check % 10;
	//calculate actual check value
	$check = 10 - $check;
	
	$checkdigit=$ch[12];
	
		if ($checkdigit==$check)
			{
			return "ISBN is valid";
			}
			else
			{
			return "ISBN is invalid";
			}
	

	}  
}


?>

</body>
</html>